const { error } = require('../utils/response');

// 手机号验证
const validatePhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

// 密码验证
const validatePassword = (password) => {
  return password && password.length >= 6 && password.length <= 20;
};

// 用户名验证
const validateUsername = (username) => {
  return username && username.length >= 2 && username.length <= 20;
};

// 用户注册验证
const validateRegister = (req, res, next) => {
  const { phone, password, username } = req.body;
  
  if (!phone) {
    return error(res, '手机号不能为空', 400);
  }
  if (!validatePhone(phone)) {
    return error(res, '手机号格式不正确', 400);
  }
  if (!password) {
    return error(res, '密码不能为空', 400);
  }
  if (!validatePassword(password)) {
    return error(res, '密码长度必须在6-20位之间', 400);
  }
  if (username && !validateUsername(username)) {
    return error(res, '用户名长度必须在2-20位之间', 400);
  }
  
  next();
};

// 用户登录验证
const validateLogin = (req, res, next) => {
  const { phone, password } = req.body;
  
  if (!phone) {
    return error(res, '手机号不能为空', 400);
  }
  if (!validatePhone(phone)) {
    return error(res, '手机号格式不正确', 400);
  }
  if (!password) {
    return error(res, '密码不能为空', 400);
  }
  
  next();
};

// 书籍ID验证
const validateBookId = (req, res, next) => {
  const { id } = req.params;
  if (!id || isNaN(parseInt(id))) {
    return error(res, '书籍ID格式不正确', 400);
  }
  next();
};

// 借阅天数验证
const validateBorrowDays = (req, res, next) => {
  const { borrowDays } = req.body;
  if (borrowDays && (isNaN(parseInt(borrowDays)) || borrowDays < 1 || borrowDays > 365)) {
    return error(res, '借阅天数必须在1-365天之间', 400);
  }
  next();
};

module.exports = {
  validateRegister,
  validateLogin,
  validateBookId,
  validateBorrowDays,
  validatePhone,
  validatePassword,
  validateUsername
};
